import { fabric } from 'fabric';

/**
 * 自定义图片类，支持遮罩和特殊渲染效果
 */
export class CustomImage extends fabric.Image {
    public maskType?: string;
    public cropShape?: string;
    public brightness?: number;
    public contrast?: number;
    public saturation?: number;
    public compositeMode?: string;

    constructor(element: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | string, options?: any) {
        super(element, options);
        this.maskType = options?.maskType || 'none';
        this.cropShape = options?.cropShape || 'rect';
        this.brightness = options?.brightness || 0;
        this.contrast = options?.contrast || 0;
        this.saturation = options?.saturation || 0;
        this.compositeMode = options?.compositeMode || 'destination-in';
    }

    /**
     * 重写渲染方法，添加自定义效果
     */
    _render(ctx: CanvasRenderingContext2D) {
        // 保存当前状态
        ctx.save();
        ctx.globalCompositeOperation = "source-over";
        // 先调用父类的渲染方法，确保图片被正确绘制
        super._render(ctx);
        // 应用遮罩效果
        if (this.maskType && this.maskType !== 'none') {
            // 使用 globalCompositeOperation 方式应用遮罩
            this._applyMask(ctx);
        }
    
        // 恢复状态
        ctx.restore();
    }

    /**
     * 应用遮罩效果 - 使用 clip() 方法实现真正的镂空效果
     */
    private _applyMask(ctx: CanvasRenderingContext2D) {
        const width = this.width || 0;
        const height = this.height || 0;
        const scaleX = this.scaleX || 1;
        const scaleY = this.scaleY || 1;
        // 保存当前状态
        ctx.save();
        // 假设已存在一个 circle.svg 的有效 URL，可以直接赋值
        const img = new Image();
        img.onload = () => {
            ctx.globalCompositeOperation = 'destination-in';

            ctx.drawImage(
                img,
                this.left || 0,
                this.top || 0,
                width * scaleX,
                height * scaleY
            );
        };
        img.src = '/circle.svg'; // 直接引用静态资源路径，或根据实际 svg 资源路径调整
    }

    /**
     * 设置遮罩类型
     */
    setMaskType(maskType: string) {
        this.maskType = maskType;
        this.setCoords();
        this.canvas?.renderAll();
    }

    /**
     * 设置合成模式
     */
    setCompositeMode(compositeMode: string) {
        this.compositeMode = compositeMode;
        this.setCoords();
        this.canvas?.renderAll();
    }


    /**
     * 设置图片滤镜
     */
    setImageFilters(brightness: number, contrast: number, saturation: number) {
        this.brightness = brightness;
        this.contrast = contrast;
        this.saturation = saturation;
        this.setCoords();
        this.canvas?.renderAll();
    }

    /**
     * 重写 toObject 方法，保存自定义属性
     */
    toObject(propertiesToInclude?: string[]) {
        return super.toObject(propertiesToInclude?.concat([
            'maskType',
            'cropShape',
            'brightness',
            'contrast',
            'saturation',
            'compositeMode'
        ]));
    }

    /**
     * 重写 fromObject 方法，恢复自定义属性
     */
    static fromObject(object: any, callback: (image: CustomImage) => void) {
        fabric.util.loadImage(object.src, (img) => {
            const image = new CustomImage(img, {
                ...object,
                maskType: object.maskType,
                cropShape: object.cropShape,
                brightness: object.brightness,
                contrast: object.contrast,
                saturation: object.saturation,
                compositeMode: object.compositeMode
            });
            callback(image);
        });
    }
}

// 注册自定义类到 fabric
(fabric as any).CustomImage = CustomImage;
